package com.example.myapplication.ui.news.adapter;

import android.support.v4.content.ContextCompat;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.myapplication.R;
import com.example.myapplication.model.bean.NewsChannelTable;
import com.example.myapplication.ui.wight.ItemDragHelperCallback;

import java.util.Collections;
import java.util.List;

/**
 * Created by meishiyiyun on 2017/6/7.
 */

public class ChannelAdapter extends BaseQuickAdapter<NewsChannelTable> implements  ItemDragHelperCallback.OnItemMoveListener{
    private ItemDragHelperCallback mItemDragHelperCallback;
    public ChannelAdapter(int layoutResId, List<NewsChannelTable> data) {
        super(layoutResId, data);
    }
    public void setItemDragHelperCallback(ItemDragHelperCallback itemDragHelperCallback) {
        mItemDragHelperCallback = itemDragHelperCallback;
    }
    @Override
    protected void convert(BaseViewHolder helper, NewsChannelTable newsChannelTable) {
        helper.setText(R.id.news_channel_tv,newsChannelTable.getNewsChannelName());
        if (newsChannelTable.getNewsChannelFixed()) {
            helper.setTextColor(R.id.news_channel_tv, ContextCompat.getColor(mContext,R.color.gray));
        }else{
            helper.setTextColor(R.id.news_channel_tv,ContextCompat.getColor(mContext,R.color.gray_deep));
        }
        handleLongPress(helper,newsChannelTable);
    }

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        if (isChannelFixed(fromPosition, toPosition)) {
            return false;
        }
        Collections.swap(getData(), fromPosition, toPosition);
        notifyItemMoved(fromPosition, toPosition);
        return true;
    }
    private void handleLongPress(BaseViewHolder helper,final NewsChannelTable newsChannelTable) {
        if (mItemDragHelperCallback != null) {
            helper.itemView.setOnTouchListener((v, event) -> {
                mItemDragHelperCallback.setLongPressEnabled(newsChannelTable.getNewsChannelIndex()==0?false:true);
                return false;
            });
        }
    }
    private boolean isChannelFixed(int fromPosition, int toPosition) {
        return (getData().get(fromPosition).getNewsChannelFixed() ||
                getData().get(toPosition).getNewsChannelFixed())&&(fromPosition==0||toPosition==0);
    }
}
